package com.hmall.pay.strategy;

import com.hmall.pay.config.PayTypeConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 操作策略的上下文环境类 工具类
 * 将策略整合起来 方便管理
 */
@Component
@RequiredArgsConstructor
public class PaymentMethodFactory implements ApplicationContextAware {

    private static Map<String, PaymentMethod> paymentMethodPool = new ConcurrentHashMap<>();

    private final PayTypeConfig payTypeConfig;

    /**
     * 从配置文件中读取策略信息存储到map中
     * {
     * balance:balancePayment,
     * zfb:zfbPayment,
     * }
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        payTypeConfig.getTypes().forEach((k, v) -> {
            paymentMethodPool.put(k, (PaymentMethod) applicationContext.getBean(v));
        });
    }

    /**
     * 对外提供获取具体策略
     *
     * @param payType 用户的支付方式，需要跟配置文件中匹配
     * @return 具体策略
     */
    public PaymentMethod getPaymentMethod(String payType) {
        return paymentMethodPool.get(payType);
    }
}
